#include "sql_data.h"

#include <QDebug>
#include <QSqlError>
#include <QElapsedTimer>
#include <thread>
#include <chrono>

bool CSQLData::connet2DB(QString dbNmae)
{
    // 初始化数据库连接
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName(dbNmae);  // 设置数据库文件名
    if (!m_db.open()) {
        m_db_open = false;
        return false;
    }
    m_db_open = true;
    m_query = new QSqlQuery(m_db);

    // 开启事务
    m_db.transaction();
    return true;
}


void CSQLData::processImages()
{
    bool RunFirstTime = false;
    static int LastEventLevel = 0;
    while (!m_stop) {

        if (!m_db_open)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            continue;
        }

        std::tuple<cv::Mat, QString, QString, int> data;

        {
            std::lock_guard<std::mutex> lock(queueMutex);
            if (!m_imageQueue.isEmpty()) {
                data = m_imageQueue.dequeue();
            }
        }

        cv::Mat saveImage = std::get<0>(data);
        if (saveImage.empty())
            continue;

        QString filePath = std::get<1>(data);
        if (filePath.isEmpty())
            continue;

        QString timeData = std::get<2>(data);
        if (timeData.isEmpty())
            continue;

        int lastUnderscoreIndex = filePath.lastIndexOf('_');
        QStringList parts = filePath.split('_', Qt::SkipEmptyParts);
        QString stopregpointer,pointers;
        if (lastUnderscoreIndex != -1) {
            //QString dateTimePart = filePath.left(lastUnderscoreIndex + 1);
            QString stopregpointerPart = filePath.mid(lastUnderscoreIndex + 1);
            stopregpointerPart.chop(4);
            stopregpointer = stopregpointerPart;
            if (!stopregpointer.isEmpty())
            {
                int secondLastUnderscore = filePath.lastIndexOf('_', lastUnderscoreIndex - 1);
                pointers = filePath.mid(secondLastUnderscore + 1, lastUnderscoreIndex - secondLastUnderscore - 1);
            }
        }
        //500ms内只保存一张。入侵和卷缠分开算
        int event_level = std::get<3>(data);
        //if (std::get<0>(data).cols != 0 && std::get<0>(data).rows != 0) { // 检查图像是否有效
        QDateTime dateTimeobject = QDateTime::fromString(timeData, "yyyy-MM-dd_hh_mm_ss.zzz_");
        int msecsDifference = currentDateTimeobject_.msecsTo(dateTimeobject);
        if (7 == event_level || 6 == event_level || 
            msecsDifference > 500 || !RunFirstTime || event_level != LastEventLevel) {
            RunFirstTime = true;
            LastEventLevel = event_level;
            currentDateTimeobject_ = dateTimeobject;
            // 写入图片到磁盘
            cv::imwrite(filePath.toStdString(), saveImage);
            //QElapsedTimer timer;
            //timer.start(); // 开始计时

            if (7 != event_level && 6 != event_level)
            {
                // 插入路径到数据库
                m_query->prepare("INSERT INTO AlarmImages_2024_Q4 (time, event_level, pointers, stopreginpointer,file_path) "
                    "VALUES (:time, :event_level, :pointers ,:stopreginpointer,:file_path)");

                m_query->bindValue(":time", timeData);
                m_query->bindValue(":event_level", event_level);
                m_query->bindValue(":pointers", pointers);
                m_query->bindValue(":stopreginpointer", stopregpointer);
                m_query->bindValue(":file_path", filePath);

                if (!m_query->exec()) {
                    qDebug() << "数据库插入失败:" << m_query->lastError();
                    m_db.rollback();  // 回滚事务
                }
                //qint64 elapsedTime = timer.elapsed(); // 以毫秒为单位的时间

                if (m_count > 10)
                {
                    m_count = 0;
                    m_db.commit();
                }
                m_count++;
            }
            //qDebug() << "nCount:" << m_count++ << " imageQueue - size : " << m_imageQueue.size() << " costtime : " << elapsedTime;
        }
        else {
            //std::this_thread::sleep_for(std::chrono::milliseconds(10));
            //qDebug() << "+++++++ sleep 10ms";
            continue;
        }
    }
}
